package org.servlet;

import org.domain.Account;
import org.domain.Cart;
import org.service.CartService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class ViewCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/JSP/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/JSP/common/Error.jsp";
    private CartService cartService;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        cartService = new CartService();
        HttpSession session = request.getSession();
        if(session.getAttribute("account")==null)
        {
            session.setAttribute("message","Please Sign In At First!");
            request.getRequestDispatcher(ERROR).forward(request,response);
        }
        else
        {
            Account account = (Account)session.getAttribute("account");
            Cart cart = cartService.getCartByUserId(account.getUsername());
            if(cart==null) cart = new Cart();
            session.setAttribute("cart",cart);
        }

        request.getRequestDispatcher(VIEW_CART).forward(request,response);
    }
}
